<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name='format-detection' content='telephone=no'>
<meta name='viewport' content='width=device-width, minimum-scale=1.0, maximum-scale=1.0'>
<title>游密IM网页版</title>
<link rel="stylesheet" type="text/css" href="./css/style.css">
<style type="text/css">
.item-rbox .clearfix{position: relative; height: 38px;}
.login-box .item-rbox .item-title{ width: 100px;}
.login-box .item-rbox .item-input{left: 120px;}
.login-box .item-input .checkbox{width: auto; border-radius: 2px; border:1px #ccc solid; vertical-align: middle; padding: 5px;}
</style>
</head>
<body>

<article class="wrapper groupim-page" id="J_groupim-page">
<section class="content-box" id="J_groupim-content-box">
    <ul class="userchat-list" id="J_userchat-list">
        
    </ul>
</section>

<div class="login-mask" id="J_login-mask"></div>
<div class="login-box" id="J_login-box">
    <div class="item-box login-msg" id="J_login-msg"></div>

    <div class="item-box item-ubox">
        <div class="item-title">用户名</div>
        <div class="item-input">
            <input type="text" class="input-text" id="J_inp-username" value="sanji" placeholder="输入用户名">
        </div>
    </div>

    <div class="item-box item-ubox">
        <div class="item-title">TOKEN</div>
        <div class="item-input">
            <input type="text" class="input-text" id="J_inp-userpwd" value="10001" placeholder="输入TOKEN">
        </div>
    </div>

    <div class="item-box item-rbox">
        <div class="clearfix">
            <div class="item-title">房间号</div>
            <div class="item-input">
                <input type="text" class="input-text" id="J_inp-roomid" value="2011234" placeholder="输入房间号">
            </div>
        </div>
        
        <div class="clearfix" style="width:180px;">
            <div class="item-title">是否显示进度</div>
            <div class="item-input" style="width:50px;">
                <input class="checkbox" type="checkbox" id="J_progress-check" checked="checked">
            </div>
        </div>
    </div>

    <div class="login-footer">
        <a href="javascript:void(0);" class="comm-btn" id="J_btn-login">登录</a>
        <a href="javascript:void(0);" class="comm-btn" id="J_btn-join">加入房间</a>
    </div>
</div>

<div class="mic-notice" id="J_mic-notice">上划取消发送</div>

<div class="common-footer voice-footer" id="J_groupim-footer">
    <a href="javascript:void(0);" type="ok"  id="J_btn-voice" class="comm-btn btn-voice"></a>
    <div class="finput-box">
        <input type="text" class="send-inp" id="J_inp-content" placeholder="输入内容...">
        <a href="javascript:void(0);" class="voice-inp" id="J_voice-inp">按住 说话</a>
    </div>

    <div class="send-btn-box">
        <a href="javascript:void(0);" type="ok"  id="J_btn-send" class="comm-btn btn-send">发送</a>
    </div>
</div>

</article>

<script type="text/template" id="J_temp-chatitem">
<li>
    <div class="user-header">
        <img class="img-auto" src="{header}" alt="">
    </div>
    <div class="box">
        <div class="uname"></div>
        <div class="content"></div>
    </div>
</li>
</script>


<script type="text/javascript">
window.onerror = function(err, l, o){
    alert(err+'; '+l+'; '+o);
};
if(location.href.indexOf('showlog')>-1){
    window.console.log = function(msg){
        yim.app.addTipsDom(msg);
    }
}
</script>

<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script type="text/javascript" src="./js/zepto-1.1.6.min.js"></script>
<script type="text/javascript" src="../yim.min.js"></script>
<script type="text/javascript" src="./js/main.js"></script>

<script type="text/javascript" src="./js/keyword.js"></script>

<script type="text/javascript">
$(document).ready(function(){
yim.debug = true;

window.g_yimInstance='';
//APPID请在游密控制台申请
var APPID = "YOUMEBC2B3171A7A165DC10918A7B50A4B939F2A187D0";

var _eventObject = {
    onLogin: function(errorcode, eve){
        console.log(errorcode, eve);
        g_yimInstance.userInfo = g_yimInstance.userInfo || {}
        if(errorcode == yim.YIMErrorcode.YIMErrorcode_Success){
            g_yimInstance.userInfo.uname = eve.data.userid;
            $('#J_login-msg').text("登录成功 :" + eve.data.userid).show();
            $('#J_login-box').addClass('room-box');
			yim.app.addTipsDom('登录成功');
        }else{
            $('#J_login-msg').text("登录失败 :" + eve.data.userid + "  错误码:" + errorcode).show();
			yim.app.addTipsDom('登录失败');
        }
    },
    onLogout: function(errorcode, eve){
        console.log(errorcode, eve);
        yim.app.addTipsDom('退出成功: '+eve.data.userid);
    },
    onJoinChatRoom: function(errorcode, eve){
        var msg = "加入房间: " + eve.data.roomid + " 错误码：" + errorcode;
        if(errorcode == yim.YIMErrorcode.YIMErrorcode_Success){
            yim.app.addTipsDom(msg);
            $('#J_login-box, #J_login-mask').hide();
        }else{
            $('#J_login-msg').text(msg).show();
        }
    },
    onLeaveChatRoom: function(errorcode,eve){
        console.log(eve);
        yim.app.addTipsDom("加入房间: " + eve.data.roomid + " 错误码：" + errorcode);
    },
    onSendMessageStatus: function(errorcode, eve){
        console.log(eve);
        console.log("OnSendMessageStatus :" + errorcode + " messageID: " + eve.data.msgid);
        if(errorcode != yim.YIMErrorcode.YIMErrorcode_Success){
            $('.text[data-msgid="'+eve.data.msgid+'"]').addClass('msg-error');
        }
    },
    onRecvMessage: function(message){
        if(message.msgType == yim.MessageBodyType.MessageBodyType_Text){
            //文本消息
            yim.app.addTextDom({
                msgSenderUID: message.senderid,
                msgRecvUID: message.recvid,
                msgId: message.messageid,
                msgTime: message.createtime,
                msgText: g_yimInstance.keywordsFilter(message.content),
                myself: false
            });
        }else if(message.msgType == yim.MessageBodyType.MessageBodyType_Voice){
            //接收到语音消息
            if(message.content.charAt(0)!='[' && message.content.charAt(0)!='{'){
                return console.error('error format msg:'+message.content);
            }

            var content = JSON.parse(message.content);
            //添加到自动播放列表
            g_yimInstance.addToAutoPlayVoiceQueue(message);

            if(content.recordmode == yim.MessageVoiceType.WEIXIN){
                //微信录音
                yim.app.addVoiceDom({
                    myself: false,
                    msgId: message.messageid,
                    msgRecvUID: message.recvid,
                    msgSenderUID: message.senderid,
                    voiceID: content.mediaid,
                    voiceSize: +content.voicetime || 12,
                    chatType: message.chattype,
                    msgTime: message.createtime
                });
            } else { //普通语音
                yim.app.addVoiceDom({
                    myself: false,
                    msgId: message.messageid,
                    msgRecvUID: message.recvid,
                    msgSenderUID: message.senderid,
                    voiceURL: content.downloadurl,
                    voiceSize: +content.voicetime || 12,
                    chatType: message.chattype,
                    msgTime: message.createtime
                });
            }
        }
    },
    onKickOff: function(){
        yim.app.addTipsDom('你被踢出了房间！');
    },
    onVoiceMsgSend: function(code, info){
        if(code != yim.YIMErrorcode.YIMErrorcode_Success){
            console.error('send voice message fail!');
            return ;
        }

        //播放自己的录音
        //g_yimInstance.playAudioMessage(info.voiceServerID);

        yim.app.addVoiceDom({
            myself: true,
            msgId: info.msgID,
            msgRecvUID: '',
            msgSenderUID: g_yimInstance.userInfo.uname,
            voiceURL: info.voiceURL,
            voiceID: info.voiceServerID,
            voiceSize: Math.floor(info.voiceTime) || 12
        });
    },
    onReceiveMessageNotify: function(chatType,targedID){
        yim.app.addTipsDom('OnReceiveMessageNotify: ' + chatType + ' targetid:' + targedID);
    },

    onReLogin: function(errorcode, eve){
        var msg = "重新登录: " + eve.data.userid + " 错误码：" + errorcode;
        yim.app.addTipsDom(msg);
    },

    onReJoinChatRoom:function(errorcode, eve){
        var msg = "重新加入房间: " + eve.data.roomid + " 错误码：" + errorcode;
        yim.app.addTipsDom(msg);
    }
};

//点击登录
$('#J_btn-login').on('click', function(){
    //登出
    //g_yimInstance.logout();
    var uname = $('#J_inp-username').val(),
        utoken = $("#J_inp-userpwd").val();
    g_yimInstance.login(uname, utoken);

    if(localStorage.setItem){ //缓存起来
        localStorage.setItem('youme-uname', uname);
        localStorage.setItem('youme-utoken', utoken);
    }
    return false;
});

var _gRoomID = '';
//点击加入房间
$('#J_btn-join').on('click', function(){
    _gRoomID = $("#J_inp-roomid").val();
    g_yimInstance.joinRoom(_gRoomID);

    yim._showProgressTips = $('#J_progress-check').prop('checked');

    //初始化语音设备
    g_yimInstance.initAudioMedia({
        //是否显示上传/下载语音提示
        showProgressTips: 1,
        //最大语音1分钟
        maxRecordSecond: 60,
        //webrtc录音
        bitRate: 64,

        mp3Worker: './js/mp3Worker.js',
        lamejs: './lame.min.js'
    }, function(ret){
        console.log("录音类型 :" + ret.type+'; 支持:'+(ret.support?1:0));
        if(!ret.support){
            yim.app.addTipsDom('当前版本不支持发送语音！');
        }
    });

    //初始化语音自动播放队列
    g_yimInstance.initAutoPlayVoiceQueue({
        beginPlay: function(msg){
            console.log('start play!', msg);
        },endPlay: function(msg){
           console.log('end play!', msg);
        }
    });

    if(yim.isWeixin()){
        //微信鉴权，参考：https://mp.weixin.qq.com/wiki
        signatureWechat(function(weixinConfig){
            wx.config({
                debug: false,
                appId: weixinConfig.appid,
                timestamp: weixinConfig.time,
                nonceStr: weixinConfig.nonce,
                signature: weixinConfig.sign,
                jsApiList: ['checkJsApi','startRecord','stopRecord','playVoice','stopVoice','onVoicePlayEnd','downloadVoice','uploadVoice']
            });
        });
    }

    //离开房间
    //g_yimInstance.leaveRoom(_gRoomID);
    return false;
});

//点击发送文字消息
yim.app.init('onTextBtnClick', function(text){
    var chatType = 2; //1:私聊; 2:群聊
    var recvUid = _gRoomID;
    var serial = g_yimInstance.sendTextMessage(recvUid, chatType, text);
    console.log('send msg:'+serial);
    yim.app.addTextDom({
        myself: true,
        msgId: serial,
        msgText: text,
        msgRecvUID: '',
        msgSenderUID: g_yimInstance.userInfo.uname
    });
});

var _lastMediaObj = '';

//点击语音消息
yim.app.init('onVoiceMsgClick', function(){
    var $this = $(this),
        msgid = $this.attr('data-msgid'),
        voiceid = $this.attr('data-voiceid'),
        voiceurl = $this.attr('data-voiceurl');

    if($this.hasClass('playing')){
        g_yimInstance.stopPlayAudioMessage(_lastMediaObj, function(code, res){
            if(code != yim.YIMErrorcode.YIMErrorcode_Success){
                return alert(res.errMsg);
            }
        });
        return $this.removeClass('playing');
    }

    _lastMediaObj = voiceid || voiceurl;
    if(!yim.isWeixin() && _lastMediaObj.substr(0,2)!='//' && _lastMediaObj.substr(0,4)!='http'){
        yim.app.addTipsDom('只能在微信客户端播放: '+_lastMediaObj);
    }else{
        $this.addClass('playing');
        g_yimInstance.playAudioMessage(_lastMediaObj, function(code, res){
            if(code != yim.YIMErrorcode.YIMErrorcode_Success){
                return alert(res.errMsg);
            }
            $('.voice[data-msgid="'+msgid+'"]').removeClass('playing');
        });
    }
});

//开始录音
yim.app.init('startRecord', function(callback){
    if(!g_yimInstance.getSupportAudioMessage()){
        return yim.app.addTipsDom('当前设备不支持录音');
    }

    var chatType = 2; //1:私聊; 2:群聊
    var recvUid = _gRoomID;

    g_yimInstance.startAudioMessage(recvUid, chatType, function(code, res){
        callback(code, res);
        if(code != yim.YIMErrorcode.YIMErrorcode_Success){
            yim.app.hideRecordUI();
            //可能用户禁用了微信语音
            alert(res.errMsg);
        }
        //yim.app.addTipsDom(code);
    });
});

//取消录音
yim.app.init('cancelRecord', function(){
    g_yimInstance.cancelAudioMessage(function(code, res){
        yim.app.hideRecordUI();
        if(code != yim.YIMErrorcode.YIMErrorcode_Success){
            return alert(res.errMsg);
        }
        console.log('cancel record:', res);
    });
});

//结束录音
yim.app.init('stopRecord', function(voiceTime){
    g_yimInstance.stopAudioMessage(function(code, res){
        yim.app.hideRecordUI();
        if(code != yim.YIMErrorcode.YIMErrorcode_Success){
            return ;//alert(res.errMsg);
        }
        console.log('stop record:', res);
    });
});

//微信鉴权封装方法
var signatureWechat = function(callback){ //wxtest3.youme.im/api/signatureinfo/
    var url = '//wxtest3.youme.im/api/signatureinfo?url='+encodeURIComponent(location.href);
    yim.jsonp({
        url : url,
        dataType : 'jsonp',
        jsonpCallback : '_yimcallback',
        success : function(jdata){
            callback(jdata);
        }
    });
};


if(localStorage.getItem){ //读取缓存的用户信息
    var uname = localStorage.getItem('youme-uname') || 'sanji';
    var utoken = localStorage.getItem('youme-utoken') || '10001';
    $('#J_inp-username').val(uname),
    $("#J_inp-userpwd").val(utoken);
}

//初始化
g_yimInstance  = new yim.getInstance(myKeywordArray, APPID, _eventObject);

g_yimInstance.socketio.on('connect', function(){
    yim.app.addTipsDom('socket connected!');
});

/*g_yimInstance.socketio.on('error', function(){
    yim.app.addTipsDom('socket error!');
});

g_yimInstance.socketio.on('send', function(key, jdata){
    yim.app.addTipsDom(jdata);
});

g_yimInstance.socketio.on('message', function(event){
    yim.app.addTipsDom(event.data);
});*/

});
</script>

</body>
</html>
